/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PodnosenjeZahtjevaKMPanel.java
 *
 * Created on Nov 24, 2010, 5:19:35 PM
 */
package hraplication;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Nermin
 */
public class PodnosenjeZahtjevaKMPanel extends Paneli {

    Konekcija kon;
    int idUposlenika;

    /** Creates new form PodnosenjeZahtjevaKMPanel */
    public PodnosenjeZahtjevaKMPanel(Konekcija konekcija) {
        initComponents();
        kon = konekcija;
        OsvjeziChBOX();
        
    }

    public void setIDuposlenika(int IDuposlenika){
        idUposlenika = IDuposlenika;
    }
     public void OsvjeziChBOX(){

        materijalCombo.removeAllItems();
        ResultSet r = kon.Select("SELECT Naziv FROM materijali");
        if (r!=null){
            try{
                while (r.next()){
                    materijalCombo.addItem(r.getString("naziv"));
                }
            }
            catch (SQLException ex)
            {
              System.err.println(ex.getMessage());
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        kolicinaField = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        tabelaPanel = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        materijalCombo = new javax.swing.JComboBox();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Zahtjev za kancelarijskim materijalom"));
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(hraplication.HRaplicationApp.class).getContext().getResourceMap(PodnosenjeZahtjevaKMPanel.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        kolicinaField.setName("kolicinaField"); // NOI18N

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        tabelaPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Odabrani materijal"));
        tabelaPanel.setName("tabelaPanel"); // NOI18N

        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Naziv", "Kolicina"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabela.setName("tabela"); // NOI18N
        tabela.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tabelaKeyReleased(evt);
            }
        });
        tabelaPanel.setViewportView(tabela);

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        materijalCombo.setName("materijalCombo"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tabelaPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 473, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 370, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton2))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(materijalCombo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(kolicinaField, javax.swing.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE)
                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(240, 240, 240)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(materijalCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(kolicinaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(tabelaPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton2)
                .addContainerGap(83, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            String materijal = materijalCombo.getSelectedItem().toString();
            int kolicina;
            try
            {
                // the String to int conversion happens here
                kolicina = Integer.parseInt(kolicinaField.getText().trim());
            }
            catch (NumberFormatException nfe)
            {
                JOptionPane.showMessageDialog(this, "Neispravna unesena kolicina!", "Info",WIDTH,null);
                return;
            }

            DefaultTableModel m = (DefaultTableModel) tabela.getModel();
            //Pretraga da li vec postoji stavka u narudzbi
            int i;
            for (i=0; i<m.getRowCount(); i++){
                if (materijal.equals(m.getValueAt(i, 0)))
                    break;
            }
            if (i==m.getRowCount()){  //ukoliko ne postoji stavka, dodaj je
                if (kolicina > 0)
                    m.insertRow(m.getRowCount(), new Object[]{materijal, kolicina});
            }
            else{ //inace povecaj kolicinu
                int trenutno = (Integer)m.getValueAt(i, 1);
                trenutno+=kolicina;
                m.setValueAt(trenutno, i, 1);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        InsertZahtjeva();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void tabelaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tabelaKeyReleased
        if (evt.getKeyCode() == evt.VK_DELETE){
            if (tabela.getSelectedRowCount()==0){
                JOptionPane.showMessageDialog(this, "Oznacite red(ove) koje zelite izbrisati!", "Info",WIDTH,null);
                return;
            }
            DefaultTableModel m = (DefaultTableModel) tabela.getModel();
            while(tabela.getSelectedRowCount()!=0)
                m.removeRow(tabela.getSelectedRow());
        }
        if (evt.getKeyCode() == evt.VK_ESCAPE){
            tabela.clearSelection();
        }
    }//GEN-LAST:event_tabelaKeyReleased

    private void InsertZahtjeva() {
        // kupiti id korisnika koji je trenutno logovan
        // dok se ta funkcionalnost ne napravi ID uposlenika se bira u listi
               
        if (tabela.getRowCount()<=0){
                JOptionPane.showMessageDialog(this, "Unesite bar jednu stavku narudzbe", "Info",WIDTH,null);
                return;
        }
        
        int id_zahtjeva = -1;
        try {
            ResultSet r = kon.Select("SELECT max(idTrebovanje) FROM podneseni_zahtjevi_za_trebovanje");
            if (r.next()) {
                id_zahtjeva = r.getInt(1) + 1;
            }

            String ins = "INSERT INTO podneseni_zahtjevi_za_trebovanje (idTrebovanje,Uposlenici_idUposlenici,Datum_podnosenja,Status_zahtjeva) VALUES(";
            ins += id_zahtjeva + "," + idUposlenika + ",CURDATE(),'PODNESEN')";
                        
            String greska = kon.Insert(ins);
            if (greska != null)
                //DOSLO DO GRESKE
                JOptionPane.showMessageDialog(this, greska, "Greska",WIDTH,null);
            else{
                if(!InsertTrebovanogMaterijala(id_zahtjeva))
                    return;  //Doslo do greske
                //ukoliko nema greske resetuj sve komponente za unos
                kolicinaField.setText("");
                materijalCombo.setSelectedIndex(0);
                DefaultTableModel m = (DefaultTableModel) tabela.getModel();
                m.getDataVector().removeAllElements();
                tabela.repaint();
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Boolean InsertTrebovanogMaterijala(int id_zahtjeva) {
        int id_materijala = -1;
        try {
            DefaultTableModel model = (DefaultTableModel) tabela.getModel();
            for (int i = 0; i < model.getRowCount(); i++) {
                String materijal = model.getValueAt(i, 0).toString();
                ResultSet r = kon.Select("SELECT idMaterijali FROM materijali where naziv ='" + materijal + "'");
                if (r.next()) {
                    id_materijala = r.getInt(1);
                }
                String ins = "INSERT INTO trebovani_materijali (idTrebovanje,Materijali_idMaterijali,Trebovana_kolicina) VALUES(";
                ins += id_zahtjeva + "," + id_materijala + "," + model.getValueAt(i, 1).toString() + ")";

                String greska = kon.Insert(ins);
                if (greska != null){
                    //DOSLO DO GRESKE
                    JOptionPane.showMessageDialog(this, greska, "Greska",WIDTH,null);
                    return false;
                }
                
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField kolicinaField;
    private javax.swing.JComboBox materijalCombo;
    private javax.swing.JTable tabela;
    private javax.swing.JScrollPane tabelaPanel;
    // End of variables declaration//GEN-END:variables
}
